package com.zhb.untils;

/**
 * @Description TODO
 * @Author Bigbo
 * @Date 2023/5/3 17:35
 * @Version 1.0
 */
import com.jcraft.jsch.*;
import com.zhb.Dto.Result;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Properties;

public class OperateLinux {
    private static Session session = null;
    private static int timeout = 60000;
    private  static ChannelExec channelExec;

    /**
     * 连接远程服务器
     * @param hostname 为远程linux 服务器
     * @param username linux用户名
     * @param  password linux登录密码
     * @param port linux 登录端口号
     */
    public static void connect(String hostname, String username, String password, int port) throws Exception{
        System.out.println("尝试连接到...host:"+hostname+", 登录名为："+username+",端口号为："+port);
        Channel channel  = null;
        JSch jsch = new JSch(); // 创建jsch 对象
        //连接服务器，如果端口小于等于0，采用默认端口，如果大于0，使用指定的端口
        if(port <=0)
        {
            //连接服务器，采用默认端口
            session = jsch.getSession(username,hostname);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(username, hostname, port);
        }
        //如果服务器连不上，则抛出异常
        if(session == null)
        {
            throw new Exception("session is nuoll");
        }
        //设置登录主机的密码
        session.setPassword(password);
        //设置第一次登录的时候的提示，可选择(ask | yes | no)
        // session.setConfig("StrictHostKeyChecking", "no");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking","no");
        session.setConfig(sshConfig);
        // 设置登陆超时时间ms
        session.setTimeout(timeout);
        session.connect();
        System.out.println("Session connected.");
        System.out.println("Opening Channel.");
    }

    /**
     * 在远程服务器上执行命令
     * @param cmd 要执行的命令字符串
     * @param charset 编码
     * @throws Exception
     */


    public static String execute(String cmd, String charset) throws Exception{

        channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(cmd);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        String result ="";
        while ((buf = reader.readLine()) != null){
            System.out.println(buf);
            result = result + buf;
        }
        reader.close();
        channelExec.disconnect();
        return result;
    }
    /**
     * 执行命令
     *
     * @param command
     * @return
     * @throws Exception
     */
    public static Result executeShell(String command) throws Exception {
        Result result = new Result();
        byte[] tmp = new byte[1024];
        StringBuffer extBuffer = new StringBuffer(); // 命令返回的结果
        StringBuffer stdBuffer = new StringBuffer(); // 命令返回的结果

        Channel channel = session.openChannel("exec");
        ChannelExec exec = (ChannelExec) channel;
        // 返回结果流（命令执行错误的信息通过getErrStream获取）
        InputStream stdStream = exec.getInputStream();
        InputStream errStream = exec.getErrStream();
        InputStream extInputStream = exec.getExtInputStream();

        exec.setCommand(command);
        exec.connect();

        try {
            // 开始获得SSH命令的结果
            while (true) {
                while (stdStream.available() > 0) {
                    int i = stdStream.read(tmp, 0, 1024);

                    if (i < 0) break;
                    stdBuffer.append(new String(tmp, 0, i));
                }
                if (exec.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            while (true) {


                while (extInputStream.available() > 0) {
                    int i = extInputStream.read(tmp, 0, 1024);
                    if (i < 0) break;
                    extBuffer.append(new String(tmp, 0, i));
                }
                if (exec.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } finally {
            //关闭连接
            channel.disconnect();
        }
        result.setError(extBuffer.toString());
        result.setOutput(stdBuffer.toString());
        return result;
    }


    public static void main(String[] args) {
        //测试代码
        try {
            System.out.println("连接linux 服务器：");
            connect("47.94.4.57","root","******",22);
            System.out.println("服务器已连接，准备使用mkdir创建文件夹：why");
            execute("mkdir why","UTF-8");
            System.out.println("why文件夹已创建，ls显示创建的文件");
            execute("ll","UTF-8");
            System.out.println("准备使用linux命令rm删除文件夹why");
            execute("rm -rf why","UTF-8");
            System.out.println("文件夹why 已通过命令删除");
            System.out.println("---------------------------------------------------------------------");
            Result result = executeShell("/root/tongsuo/bin/tongsuo version");
            // String execute = execute("/root/tongsuo/bin/tongsuo version", "UTF-8");
            System.out.println(result.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
